package com.lgw.coupon.Schedule;

import cn.hutool.core.collection.CollectionUtil;
import com.lgw.commons.model.pojo.CouponTemplate;
import com.lgw.coupon.mapper.CouponTemplateMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class ScheduledTask {

    @Autowired
    private CouponTemplateMapper couponTemplateMapper;

    /**
     * 下线已过期的优惠券模板
     */
    @Scheduled(fixedRate = 60 * 60 * 1000)
    private void offlineCouponTemplate() {
        log.info("开始清除过期优惠券模板");

        List<CouponTemplate> templates = couponTemplateMapper.findAllByExpired(false);
        if (CollectionUtil.isEmpty(templates)) {
            log.info("过期优惠券已清除");
            return;
        }
        Date cur = new Date();
        List<Integer> ids = new ArrayList<>(templates.size());
        //根据"过期时间"判断是否已过期 过期修改标记->添加到待处理过期List中->存储数据库  && 启到过滤过期的功能 解决定时的弊端
        templates.forEach(t -> {
            Date deadline = t.getDeadline();
            if (deadline.getTime() <= cur.getTime()) {
                ids.add(t.getId());
            }
        });
        if (!CollectionUtils.isEmpty(ids)) {
            //
            log.info("过期优惠券数量：{}", couponTemplateMapper.updateAllexpired(ids));
        }
        log.info("过期优惠券已清除");
    }


}
